from django.db import models
from django.conf import settings

class Category(models.Model):
    name = models.CharField(max_length=100)  # 分类名称
    color = models.CharField(max_length=7)  # 分类颜色（十六进制代码）

    def __str__(self):
        return self.name

class Question(models.Model):
    title = models.CharField(max_length=255)  # 问题标题
    content = models.TextField()  # 问题内容
    created_at = models.DateTimeField(auto_now_add=True)  # 创建时间
    updated_at = models.DateTimeField(auto_now=True)  # 更新时间
    pinned = models.BooleanField(default=False)  # 是否置顶
    views = models.IntegerField(default=0)  # 浏览次数
    category = models.ForeignKey(Category, related_name='questions', on_delete=models.CASCADE)  # 所属分类
    author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='questions', on_delete=models.CASCADE)  # 问题作者
    best_answer = models.ForeignKey('Answer', related_name='best_for_questions', on_delete=models.SET_NULL, null=True, blank=True)  # 采纳的最佳答案

    def __str__(self):
        return self.title

class Answer(models.Model):
    question = models.ForeignKey(Question, related_name='answers', on_delete=models.CASCADE)  # 所属问题
    content = models.TextField()  # 答案内容
    created_at = models.DateTimeField(auto_now_add=True)  # 创建时间
    updated_at = models.DateTimeField(auto_now=True)  # 更新时间
    author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='answers', on_delete=models.CASCADE)  # 答案作者

    def __str__(self):
        return f'Answer to {self.question.title} by {self.author.username}'
